//
//  UIGestureRecognizer.swift
//  CMKit
//
//  Created by travel on 2016/12/15.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import UIKit


private var cm_UIGestureRecognizer_block_key:Void?
public extension UIGestureRecognizer {
    
    class _CMUIGestureRecognizerTarget:NSObject {
        var block:((_:AnyObject?)->Void)?
        init(block:((_:AnyObject?)->Void)?) {
            self.block = block
        }
        func invoke(_ sender:AnyObject?) {
            self.block?(sender)
        }
    }
    
    
    /// 初始化手势，
    ///
    /// - Parameter block: 回调 block
    public convenience init(block:((_:AnyObject?)->Void)?) {
        self.init()
        self.addActionBlock(block)
    }
    
    
    /// 手势添加回调 block
    ///
    /// - Parameter block:  回调 block
    public func addActionBlock(_ block:((_:AnyObject?)->Void)?) {
        let target = _CMUIGestureRecognizerTarget(block: block)
        self.addTarget(target, action: #selector(_CMUIGestureRecognizerTarget.invoke(_:)))
        self.cm_allUIGestureRecognizerBlockTargets().add(target)
    }
    
    
    /// 删除所有回调
    public func removeAllActionBlock() {
        let targets = self.cm_allUIGestureRecognizerBlockTargets()
        for t in targets {
            self.removeTarget(t, action: #selector(_CMUIGestureRecognizerTarget.invoke(_:)))
        }
        targets.removeAllObjects()
    }
    
    private func cm_allUIGestureRecognizerBlockTargets() -> NSMutableArray {
        var ary = objc_getAssociatedObject(self, &cm_UIGestureRecognizer_block_key)
        if(ary == nil) {
            ary = NSMutableArray()
            objc_setAssociatedObject(self, &cm_UIGestureRecognizer_block_key, ary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        return ary as! NSMutableArray
    }
    
}
